//
//  WBEngineTX.m
//  PUDemo
//
//  Created by JK.Peng on 13-2-22.
//  Copyright (c) 2013年 njut. All rights reserved.
//

#import "WBEngineTX.h"
#import "SFHFKeychainUtils.h"

#define kWBTxTokenKey           @"access_token"

#define kWBKeychainOauth2TXUserId [NSString stringWithFormat:@"%@_WeiBoOauth2TXUserId",[self urlSchemeString]]
#define kWBKeychainOauth2TXOpenId [NSString stringWithFormat:@"%@_WeiBoOauth2TXOpenId",[self urlSchemeString]]

@implementation WBEngineTX
@synthesize userId = _userId;
@synthesize openId = _openId;

- (id)initWithAppKey:(NSString *)theAppKey appSecret:(NSString *)theAppSecret
{
    self = [super initWithAppKey:theAppKey appSecret:theAppSecret type:kOFTypeTX];
    if (self) {
    }
    return self;
}

- (void)dealloc
{
    [_userId release], _userId = nil;
    [_openId release], _openId = nil;
    [super dealloc];
}

#pragma mark - WBAuthorizeOauth2DataSource
/*
 第一步：请求code
 
 请求方法：
 GET
 请求地址：
 https://open.t.qq.com/cgi-bin/oauth2/authorize?client_id=APP_KEY&response_type=code&redirect_uri=http://www.myurl.com/example
 */
- (NSString *)authorizeOauth2AuthorizeURL:(OFAuthorizeOauth2 *)authorize
{
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                    _appKey, @"client_id",
                                    TX_REDIRECT_URI, @"redirect_uri",
                                    @"code", @"response_type",
                                    @"2", @"wap",
                                    nil];
    
    return [OFRequest serializeURL:@"https://open.t.qq.com/cgi-bin/oauth2/authorize"
                            params:params
                        httpMethod:@"GET"];
}
/*
 第二步：请求accesstoken
 
 请求地址：
 https://open.t.qq.com/cgi-bin/oauth2/access_token?client_id=APP_KEY&client_secret=APP_SECRET&redirect_uri=http://www.myurl.com/example&grant_type=authorization_code&code=CODE
 */
- (OFRequest *)authorizeOauth2WBRequestForAccessToken:(OFAuthorizeOauth2 *)authorize authorizeCode:(NSString *)code
{
    
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                    _appKey, @"client_id",
                                    _appSecret, @"client_secret",
                                    TX_REDIRECT_URI, @"redirect_uri",
                                    @"authorization_code", @"grant_type",
                                    code,@"code",
                                    nil];
    
    return [self generateRequestWithUrl:@"https://open.t.qq.com/cgi-bin/oauth2/access_token"
                             httpMethod:@"GET"
                                 params:params
                           postDataType:kOFRequestPostDataTypeNone
                       httpHeaderFields:nil
                               delegate:authorize];
}

#pragma mark - OFAuthorizeOauth2Delegate
- (OFAuthorizeParseResult *)authorizeOauth2:(OFAuthorizeOauth2 *)authorize parseAuthorizeCode:(NSString *)string
{
    OFAuthorizeParseResult * result = [[[OFAuthorizeParseResult alloc] init] autorelease];
    NSArray * pairsAry = [string componentsSeparatedByString:@"&"];
    for (NSString * pairString in pairsAry) {
        NSArray * pair = [pairString componentsSeparatedByString:@"="];
        if ([pair count] == 2) {
            if ([[pair objectAtIndex:0] isEqualToString:@"code"]) {
                result.authorizeCode = [pair objectAtIndex:1];
            } else if ([[pair objectAtIndex:0] isEqualToString:@"error_code"]) {
                result.authorizeCode = [pair objectAtIndex:1];
                result.authorizeErrorCode = YES;
            } else if([[pair objectAtIndex:0] isEqualToString:@"openid"]){
                self.openId = [pair objectAtIndex:1];
            }
        }
    }
    if (result.authorizeCode) {
        return result;
    } else {
        return nil;
    }
}

- (BOOL)authorizeOauth2:(OFAuthorizeOauth2 *)authorize parseAccessToken:(NSString *)string
{
    
    NSMutableDictionary   *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    NSArray * pairsAry = [string componentsSeparatedByString:@"&"];
    
    for (NSString  *pairString in pairsAry) {
        NSArray * pair = [pairString componentsSeparatedByString:@"="];
        if ([pair count] == 2) {
            [dic setObject:[pair objectAtIndex:1] forKey:[pair objectAtIndex:0]];
        }
    }
    
    self.accessToken = [dic objectForKey:@"access_token"];
    self.userId = [dic objectForKey:@"name"];
    self.expireTime = [[dic objectForKey:@"expires_in"] doubleValue]+[[NSDate date] timeIntervalSince1970];
    
    if (self.accessToken && self.userId && self.expireTime > 0) {
        return YES;
    }
    
    return NO;
}


#pragma mark - Overwrite
- (BOOL)isLoggedIn
{
    return ([super isLoggedIn] && _userId && _openId);
}

- (void)saveAuthorizeData
{
    [[NSUserDefaults standardUserDefaults] setObject:_userId forKey:kWBKeychainOauth2TXUserId];
    [[NSUserDefaults standardUserDefaults] setObject:_openId forKey:kWBKeychainOauth2TXOpenId];
    [super saveAuthorizeData];
}

- (void)readAuthorizeData
{
    self.userId = [[NSUserDefaults standardUserDefaults] objectForKey:kWBKeychainOauth2TXUserId];
    self.openId = [[NSUserDefaults standardUserDefaults] objectForKey:kWBKeychainOauth2TXOpenId];
    [super readAuthorizeData];
}

- (void)deleteAuthorizeData
{
    self.userId = nil;
    self.openId = nil;
    [super deleteAuthorizeData];
}

#pragma mark - Private
- (OFRequest *)generateRequestWithUrl:(NSString *)url
                           httpMethod:(NSString *)httpMethod
                               params:(NSMutableDictionary *)params
                         postDataType:(OFRequestPostDataType)postDataType
                     httpHeaderFields:(NSDictionary *)httpHeaderFields
                             delegate:(id<OFRequestDelegate>)aDelegate
{
    return [self generateRequestWithUrl:url
                             httpMethod:httpMethod
                                 params:params
                           postDataType:postDataType
                       httpHeaderFields:httpHeaderFields
                               tokenKey:kWBTxTokenKey
                               delegate:aDelegate];
}

/*
 微博http请求参数（公共部分）, 请求的参数中，Oauth部分需包含:
 字段                        说明
 oauth_consumer_key         appkey
 access_token               授权获得的accesstoken
 openid                     授权获取的openid
 clientip                   客户端的ip
 oauth_version              版本号，必须为2.a
 scope                      请求权限范围（默认“all”）
 */
- (NSMutableDictionary *)commonParams
{
    NSMutableDictionary  *params = [NSMutableDictionary dictionaryWithCapacity:0];
    if (_appKey) {
        [params setObject:_appKey forKey:@"oauth_consumer_key"];
    }
    
    if (_accessToken) {
        [params setObject:self.accessToken forKey:@"access_token"];
    }
    
    if (_openId) {
        [params setObject:_openId forKey:@"openid"];
        
    }
    
    [params setObject:@"127.0.0.1" forKey:@"clientip"];
    [params setObject:@"2.a" forKey:@"oauth_version"];
    [params setObject:@"all" forKey:@"scope"];
    
    return params;
}

#pragma mark - 腾讯微博 相关API
/*
 * 1）t/add： 发表一条微博；2）t/add_pic：发表一条带图片的微博
 */
- (void)sendWeiBoWithText:(NSString *)text image:(UIImage *)image
{
    if (!text && !image) {
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:[self commonParams]];
    
    [params setObject:@"json" forKey:@"format"];
    
    if (text == nil || [text isEqualToString:@""]) {
        [params setObject:@"分享图片" forKey:@"content"];
    }else{
        [params setObject:text forKey:@"content"];
    }
    
    if (image) {
		[params setObject:image forKey:@"pic"];
        
        [self loadRequestWithUrl:@"https://open.t.qq.com/api/t/add_pic"
                      httpMethod:@"POST"
                          params:params
                    postDataType:kOFRequestPostDataTypeMultipart
                httpHeaderFields:nil];
    } else {
        [self loadRequestWithUrl:@"https://open.t.qq.com/api/t/add"
                      httpMethod:@"POST"
                          params:params
                    postDataType:kOFRequestPostDataTypeNormal
                httpHeaderFields:nil];
    }
}

//时间线/主页时间线
- (void)requestFriendsTimelineWithSinceId:(NSString *)sinceId
                                    maxId:(NSString *)maxId
                                   length:(NSInteger)length
{
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:[self commonParams]];
    
    [params setObject:@"json" forKey:@"format"];
    if (maxId) {
        [params setObject:@"1" forKey:@"pageflag"];
        [params setObject:maxId forKey:@"pagetime"];
    } else {
        [params setObject:@"0" forKey:@"pageflag"];
        [params setObject:@"0" forKey:@"pagetime"];
    }
    if (length > 0) {
        [params setObject:[NSString stringWithFormat:@"%d", length] forKey:@"reqnum"];
    }
    
    [self loadRequestWithUrl:@"https://open.t.qq.com/api/statuses/home_timeline"
                  httpMethod:@"GET"
                      params:params
                postDataType:kOFRequestPostDataTypeNone
            httpHeaderFields:nil];
}

//t/re_add 微博相关/转播一条微博
- (void)repostWeiboWithWeiboId:(NSString *)weiboId text:(NSString *)text commentType:(OFRepostCommentType)commentType
{
    if (!weiboId) {
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:[self commonParams]];
    
    //NSString *sendText = [text URLEncodedString];
    [params setObject:@"json" forKey:@"format"];
    if (text) {
        [params setObject:text forKey:@"content"];
    }
    [params setObject:weiboId forKey:@"reid"];
    
    [self loadRequestWithUrl:@"https://open.t.qq.com/api/t/re_add"
                  httpMethod:@"POST"
                      params:params
                postDataType:kOFRequestPostDataTypeNormal
            httpHeaderFields:nil];
    
    if (commentType == kOFRepostCommentCurrent || commentType == kOFRepostCommentAll) {
        WBEngineTX * engine = [[WBEngineTX alloc] initWithAppKey:self.appKey appSecret:self.appSecret oauthVer:_oauthVer type:_type];
        [engine sendCommentWithWeiboId:weiboId text:text commentOri:NO];
        [engine release];
    }
}

/*
 *t/re_list 微博相关/获取单条微博的转发或点评列表
 */
- (void)requestCommentsWithWeiboId:(NSString *)weiboId
                             maxId:(NSString *)maxId
                      maxTimestamp:(NSString *)maxTimestamp
                            length:(NSInteger)length
{
    if (!weiboId) {
        return;
    }
    
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:[self commonParams]];
    [params setObject:weiboId forKey:@"rootid"]; //转发或回复的微博根结点id（源微博id）
    [params setObject:@"1" forKey:@"flag"]; //0－转播列表 1－点评列表 2－点评与转播列表
    [params setObject:@"json" forKey:@"format"];
    if (maxId && maxTimestamp) {
        [params setObject:@"1" forKey:@"pageflag"];
        [params setObject:maxId forKey:@"twitterid"];
        [params setObject:maxTimestamp forKey:@"pagetime"];
    } else {
        [params setObject:@"0" forKey:@"pageflag"];
        [params setObject:@"0" forKey:@"twitterid"];
        [params setObject:@"0" forKey:@"pagetime"];
    }
    if (length > 0) {
        [params setObject:[NSString stringWithFormat:@"%d", length] forKey:@"reqnum"];
    }
    
    [self loadRequestWithUrl:@"https://open.t.qq.com/api/t/re_list"
                  httpMethod:@"GET"
                      params:params
                postDataType:kOFRequestPostDataTypeNone
            httpHeaderFields:nil];
}

/*
 *接口：t/comment   微博相关/点评一条微博
 */
- (void)sendCommentWithWeiboId:(NSString *)weiboId text:(NSString *)text commentOri:(BOOL)commentOri
{
    if (!weiboId || !text) {
        return;
    }
    
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:[self commonParams]];
    [params setObject:weiboId forKey:@"reid"];     //点评根结点（非父结点）微博id
    [params setObject:@"json" forKey:@"format"];
    [params setObject:text forKey:@"content"];
    
    [self loadRequestWithUrl:@"https://open.t.qq.com/api/t/comment"
                  httpMethod:@"POST"
                      params:params
                postDataType:kOFRequestPostDataTypeNormal
            httpHeaderFields:nil];
}

- (void)requestCountsWithWeiboIds:(NSArray *)weiboIds
{
    NSString * idsStr = [weiboIds componentsJoinedByString:@","];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:1];
    [params setObject:@"json" forKey:@"format"];
    [params setObject:idsStr forKey:@"ids"];
    [params setObject:@"2" forKey:@"flag"];
    [self loadRequestWithUrl:@"https://open.t.qq.com/api/t/re_count"
                  httpMethod:@"GET"
                      params:params
                postDataType:kOFRequestPostDataTypeNone
            httpHeaderFields:nil];
}

/*
 * 接口：user/info  获取自己的详细资料
 */
- (void)requestUserProfile
{
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:[self commonParams]];
    [params setObject:@"json" forKey:@"format"];
    [self loadRequestWithUrl:@"https://open.t.qq.com/api/user/info"
                  httpMethod:@"GET"
                      params:params
                postDataType:kOFRequestPostDataTypeNone
            httpHeaderFields:nil];
}

/*
 * 帐户相关/获取其他人资料
 */
- (void)requestOtherUserProfile:(NSString *)uId
{
    NSMutableDictionary * params = [NSMutableDictionary dictionaryWithDictionary:[self commonParams]];
    [params setObject:@"json" forKey:@"format"];
    if (uId) {
        [params setObject:uId forKey:@"fopenid"];
    }
    [self loadRequestWithUrl:@"https://open.t.qq.com/api/user/other_info"
                  httpMethod:@"GET"
                      params:params
                postDataType:kOFRequestPostDataTypeNone
            httpHeaderFields:nil];
}

#pragma mark - OFRequestDelegate Methods
- (void)request:(OFRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    [self retain];
    request.delegate = nil;
    [_requestAry removeObjectIdenticalTo:request];
    NSError * error = nil;
    NSDictionary * jsonDict = [self parseJSONString:result error:&error];
    BOOL failed = NO;
    if (!error) {
        if ([jsonDict isKindOfClass:[NSDictionary class]]) {
            id ret = [jsonDict objectForKey:@"ret"];
            if (ret && [ret isKindOfClass:[NSNumber class]] && [ret intValue] !=0 ) {
                failed = YES;
                id errorCodeStr = [jsonDict objectForKey:@"error_code"];
                if ([errorCodeStr intValue] == 10019 || [errorCodeStr intValue] == 37) {
                    // 授权超时
                    [self delegateEngineAuthorizeExpired];
                    [self release];
                    return;
                }
            }
        }
    } else {
        failed = YES;
    }
    
    if (failed) {
        [self delegateEngineRequestDidFailWithError:error];
    } else {
        [self delegateEngineRequestDidSucceedWithResult:jsonDict];
    }
    [self release];
}

@end
